import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'rebellion_udp_platform_interface.dart';

/// An implementation of [RebellionUdpPlatform] that uses method channels.
class MethodChannelRebellionUdp extends RebellionUdpPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('rebellion_udp');

  @override
  Future<String?> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  void close() {
    methodChannel.invokeMethod('close');
  }

  @override
  Future<void> init(String multicastAddress, int port) async {
    methodChannel.invokeMethod('init', {
      'multicastAddress': multicastAddress,
      'port': port
    });
  }

  @override
  Future<bool?> isOpen() async {
    return await methodChannel.invokeMethod<bool>('isOpen');
  }

  @override
  void listen({required Function(Uint8List p1) read, required Function() write, required Function() closed}) {
    methodChannel.setMethodCallHandler((event) {
        switch(event.method){
          case 'read':
            if (kDebugMode) {
              print("Datagram ${event.arguments}");
            }
            read(event.arguments);
            break;
          case 'write':
            write();
            break;
          case 'closed':
            closed();
            break;
        }
        return Future.value();
    });
  }

  @override
  void send(Uint8List data) {
    methodChannel.invokeMethod('send', data);
  }

  @override
  void sendToTarget(String ip, Uint8List data) {
    methodChannel.invokeMethod('sendToTarget', {
      'ip': ip, 'data': data
    });
  }
}
